#include "blockq.h"

BlockQ* blockq_create(void)
{
    //对堆上malloc空间
    BlockQ* q = (BlockQ*) malloc(sizeof(BlockQ));

    q->front = 0;
    q->rear = 0;
    q->size = 0;
    
    //初始化互斥量
    pthread_mutex_init(&q->mut, NULL);
    
    //初始化条件变量
    pthread_cond_init(&q->not_empty, NULL);
    pthread_cond_init(&q->not_full, NULL);
    return q;
}

void block_destory(BlockQ* q)
{
    //回收空间，一般按照初始化相反的顺序进行回收
    pthread_cond_destroy(&q->not_full);
    pthread_cond_destroy(&q->not_empty);
    pthread_mutex_destroy(&q->mut);
    free(q);
}

bool block_empty(BlockQ* q)
{
    //因为要对数据进行查看，所以要拿到互斥锁
    pthread_mutex_lock(&q->mut);
    E sz = q->size;
    pthread_mutex_unlock(&q->mut);
    return sz == 0;
}
bool block_full(BlockQ* q)
{
    pthread_mutex_lock(&q->mut);
    E sz = q->size;
    pthread_mutex_unlock(&q->mut);
    return sz == N;
}
void block_push(BlockQ* q, E val)
{
    //上锁
    pthread_mutex_lock(&q->mut);
    while(q->size == N)
    {
        //not_full 条件不存在
        //如果为满进入阻塞状态
        //释放所持的互斥量
        //陷入阻塞状态
        pthread_cond_wait(&q->not_full, &q->mut);
        //当函数返回时，拿到互斥量
        //可能为虚假唤醒
    }//一定满足条件阻塞队列不满
    q->elements[q->rear] = val;
    q->rear = (q->rear + 1)%N;
    q->size ++;

    //一定不为满
    pthread_cond_signal(&q->not_empty);
    pthread_mutex_unlock(&q->mut);
}
E block_pop(BlockQ* q)
{
    //上锁
    pthread_mutex_lock(&q->mut);
    while(q->size == 0)
    {
        //not_empty 条件不存在
        //进入阻塞状态，等待条件变量
        //释放所持的互斥量
        //陷入阻塞状态
        pthread_cond_wait(&q->not_empty, &q->mut);
        //当函数返回时，拿到互斥量
        //可能为虚假唤醒
    }//一定满足
    E val = q->elements[q->front];
    q->front = (q->front+1)%N;
    q->size--;
    pthread_cond_signal(&q->not_full);
    pthread_mutex_unlock(&q->mut);
    return val;
}

E block_peek(BlockQ* q)
{
    //上锁
    pthread_mutex_lock(&q->mut);
    while(q->size == 0)
    {
        //不为空不满足
        pthread_cond_wait(&q->not_empty, &q->mut);
    }
    E val = q->elements[q->front];
    pthread_mutex_unlock(&q->mut);
    return val;
}